<template>
  <div class="department-manage p-4" tabindex="0" >
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-input
        v-model="queryParams.deptName"
        placeholder="请输入部门名称"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd" ref="addButton">
        <el-icon><Plus /></el-icon>
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border>
      <el-table-column label="id" width="80" align="center" type="index">
      </el-table-column>
      <el-table-column prop="deptName" label="部门名称" min-width="150" />
      <el-table-column prop="createUser" label="创建人" min-width="120" />
      <el-table-column prop="count" label="人数" min-width="160" />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <div class="flex space-x-2">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              plain
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 部门添加/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="dialogTitle"
      :direction="direction"
      size="380px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="deptFormRef"
        :model="deptForm"
        :rules="deptFormRules"
        label-width="100px"
        @keyup.enter.native="submitForm"
      >
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="deptForm.deptName"
            placeholder="请输入部门名称"
            @keyup.enter="submitForm"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" ref="submitButton" @keyup.enter="submitForm"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>

    <!-- 部门详情对话框 -->
    <el-dialog title="部门详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="部门ID">{{
          deptDetail.id
        }}</el-descriptions-item>
        <el-descriptions-item label="部门名称">{{
          deptDetail.deptName
        }}</el-descriptions-item>
        <el-descriptions-item label="部门描述" :span="2">{{
          deptDetail.description || '暂无描述'
        }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{
          deptDetail.teacherName
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          deptDetail.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{
          deptDetail.updateTime
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import {
  getdeptlist,
  createdeptlist,
  updatadeptlist,
  deldeptlist,
} from '@/api/dept.js'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  deptName: '',
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const jumpPage = ref(1)
const addButton = ref(null)

// 抽屉相关
const drawerVisible = ref(false)
const dialogTitle = ref('添加部门')
const direction = ref('rtl') // 从右向左打开
const isEdit = ref(false)
const deptFormRef = ref(null)
const deptForm = reactive({
  deptName: '',
})
const submitButton = ref(null)

// 部门详情对话框
const detailDialogVisible = ref(false)
const deptDetail = reactive({
  id: '',
  deptName: '',
  description: '',
  createUser: '',
  createTime: '',
  updateTime: '',
})

// 表单验证规则
const deptFormRules = {
  deptName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
}

// 获取部门列表
const getDeptList = async () => {
  loading.value = true
  try {
    // 这里应调用部门列表API
    const { code, data, msg } = await getdeptlist(queryParams)
    if (code != 200) {
      ElMessage.error(msg)
      return
    }

    tableData.value = data.records
    total.value = data.total
    // 关闭loading
    loading.value = false
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getDeptList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getDeptList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getDeptList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getDeptList()
}

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加部门'
  isEdit.value = false
  // 重置表单
  Object.keys(deptForm).forEach((key) => {
    deptForm[key] = undefined
  })
  drawerVisible.value = true
  // 在表单显示后重置校验结果
  setTimeout(() => {
    deptFormRef.value?.resetFields()
  }, 0)
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑部门'
  isEdit.value = true
  // 填充表单数据
  Object.keys(deptForm).forEach((key) => {
    deptForm[key] = row[key]
  })
  drawerVisible.value = true
}

// 处理详情
const handleDetail = (row) => {
  // 填充详情数据
  Object.keys(deptDetail).forEach((key) => {
    deptDetail[key] = row[key] || ''
  })
  detailDialogVisible.value = true
}

// 处理提交表单
const submitForm = async () => {
  if (!deptFormRef.value) return

  await deptFormRef.value.validate(async (valid) => {
    if (valid) {
      // 这里应调用添加或更新部门API
      if (!isEdit.value) {
        await createdeptlist(deptForm)
      } else {
        await updatadeptlist(deptForm)
      }
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      drawerVisible.value = false
      getDeptList()
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  // 弹窗提示
  ElMessageBox.confirm(`确定要删除部门"${row.deptName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 这里应该调用删除API
      const { code, msg } = await deldeptlist(row.id)
      if (code != 200) {
        ElMessage.error(msg)
        return
      }
      ElMessage.success('删除成功')
      getDeptList()
    })
    .catch(() => {})
}

// 监听deptName变化，实现防抖搜索
let searchTimer = null
watch(
  () => queryParams.deptName,
  (newVal) => {
    if (searchTimer) clearTimeout(searchTimer)
    searchTimer = setTimeout(() => {
      handleSearch()
    }, 500) // 500毫秒防抖
  }
)

onMounted(() => {
  getDeptList()
})
</script>

<style lang="less" scoped>
.department-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}
</style>
